package com.ruoyi.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysOrder;
import com.ruoyi.common.dto.HourDTO;
import com.ruoyi.common.dto.RecordNoDTO;
import com.ruoyi.system.domain.vo.RecordNoVO;
import com.ruoyi.system.mapper.SysOrderMapper;
import com.ruoyi.system.service.ISysOrderService;
import io.lettuce.core.ScriptOutputType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单表
 */
@RestController
@RequestMapping
public class SysOrderController {

    @Autowired
    private ISysOrderService sysOrderService;

    @Autowired
    private SysOrderMapper sysOrderMapper;

/*    @PostMapping("queryTotal")
    public AjaxResult queryTotal() {

        // 查询累计已检测次数
        Long TotalNumberDetectedTimes = sysOrderService.queryTotal();
        // 查询 result 和 markType 相等的次数
        Long equals = sysOrderService.resultEqualMarkType();

        // 避免整数除法导致的误差，转换为 double 计算
        double accuracy = (TotalNumberDetectedTimes > 0)
                ? (double) equals / TotalNumberDetectedTimes
                : 0.0;

        // 格式化保留两位小数（可选）
        DecimalFormat df = new DecimalFormat("0.00");
        String formattedAccuracy = df.format(accuracy * 100) + "%";

        LambdaQueryWrapper<SysOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(SysOrder::getRecordNo)  // 只查询 record_no
                .orderByDesc(SysOrder::getCreateTime)  // 按 create_time 降序排序
                .last("LIMIT 1");  // 只取一条记录

        SysOrder latestOrder = sysOrderMapper.selectOne(wrapper);
        String recordNo = latestOrder.getRecordNo();

        //查询柱状图
        LambdaQueryWrapper<SysOrder> wrappeRecordNo0 = new LambdaQueryWrapper<>();
        wrappeRecordNo0.eq(SysOrder::getResult, 0);  // 条件：result 等于 0
        Integer result0 = sysOrderMapper.selectCount(wrappeRecordNo0);

        LambdaQueryWrapper<SysOrder> wrappeRecordNo1 = new LambdaQueryWrapper<>();
        wrappeRecordNo1.eq(SysOrder::getResult, 1);  // 条件：result 等于 0
        Integer result1 = sysOrderMapper.selectCount(wrappeRecordNo1);

        LambdaQueryWrapper<SysOrder> wrappeRecordNo2 = new LambdaQueryWrapper<>();
        wrappeRecordNo2.eq(SysOrder::getResult, 2);  // 条件：result 等于 0
        Integer result2 = sysOrderMapper.selectCount(wrappeRecordNo2);

        System.out.println("--------------------");
        //查询柱状图
        LambdaQueryWrapper<SysOrder> wrappeMarkType0 = new LambdaQueryWrapper<>();
        wrappeMarkType0.eq(SysOrder::getMarkType, 0);  // 条件：mark_type 等于 0
        Integer MarkType0 = sysOrderMapper.selectCount(wrappeMarkType0);


        LambdaQueryWrapper<SysOrder> wrappeMarkType1 = new LambdaQueryWrapper<>();
        wrappeMarkType1.eq(SysOrder::getMarkType, 1);  // 条件：mark_type 等于 0
        Integer MarkType1 = sysOrderMapper.selectCount(wrappeMarkType1);

        LambdaQueryWrapper<SysOrder> wrappeMarkType2 = new LambdaQueryWrapper<>();
        wrappeMarkType2.eq(SysOrder::getMarkType, 2);  // 条件：mark_type 等于 0
        Integer MarkType2 = sysOrderMapper.selectCount(wrappeMarkType2);



        //查询饼图
        // 确保 totalNumberDetectedTimes 不为零，防止除零异常

            // 计算各个 markType 的百分比
            double PipMarkType0 = (double) MarkType0 / TotalNumberDetectedTimes * 100;
            double PipMarkType1 = (double) MarkType1 / TotalNumberDetectedTimes * 100;
            double PipMarkType2 = (double) MarkType2 / TotalNumberDetectedTimes * 100;


            //查询result=0的数据和mark_type=0的数据的值相等的数据的数量
        LambdaQueryWrapper<SysOrder> wrapperMr0 = new LambdaQueryWrapper<>();
        wrapperMr0.eq(SysOrder::getResult, 0)  // result = 0
                .eq(SysOrder::getMarkType, 0); // mark_type = 0

        Integer wrapperMrs0 = sysOrderMapper.selectCount(wrapper);

        //查询result=0的数据和mark_type=0的数据的值相等的数据的数量
        LambdaQueryWrapper<SysOrder> wrapperMr1 = new LambdaQueryWrapper<>();
        wrapperMr1.eq(SysOrder::getResult, 1)  // result = 0
                .eq(SysOrder::getMarkType, 1); // mark_type = 0

        Integer wrapperMrs1 = sysOrderMapper.selectCount(wrapper);

        //查询result=0的数据和mark_type=0的数据的值相等的数据的数量
        LambdaQueryWrapper<SysOrder> wrapperMr2 = new LambdaQueryWrapper<>();
        wrapperMr2.eq(SysOrder::getResult, 2)  // result = 0
                .eq(SysOrder::getMarkType, 2); // mark_type = 0

        Integer wrapperMrs2 = sysOrderMapper.selectCount(wrapper);



       Integer markTypeEqualResult0 = wrapperMrs0/MarkType0;

        Integer markTypeEqualResult1 = wrapperMrs0/MarkType1;
        Integer markTypeEqualResult2 = wrapperMrs2/MarkType2;


        // 返回结果
        HashMap<String, Object> map = new HashMap<>();
        map.put("NewrecordNo", recordNo);//正在检测订单号
        map.put("TotalNumberDetectedTimes", TotalNumberDetectedTimes);//累计已检测次数
        map.put("ComprehensiveAccuracy", formattedAccuracy);//综合准确率

        map.put("result0", result0);
        map.put("result1",result1);
        map.put("result2", result2);

        map.put("MarkType0",MarkType0);
        map.put("MarkType1", MarkType1);
        map.put("MarkType2", MarkType2);


       //饼
        map.put("PipMarkType0",PipMarkType0);
        map.put("PipMarkType1",PipMarkType1);
        map.put("PipMarkType2",PipMarkType2);



        //检测结果 0
        map.put("正常",MarkType0);
        map.put("总检测次数占比",PipMarkType0);
        map.put("准确率",markTypeEqualResult0);

        //检测结果 1
        map.put("正常",MarkType1);
        map.put("总检测次数占比",PipMarkType1);
        map.put("准确率",markTypeEqualResult1);


        //检测结果 2
        map.put("正常",MarkType2);
        map.put("总检测次数占比",PipMarkType2);
        map.put("准确率",markTypeEqualResult2);


        return AjaxResult.success(map);
    }*/


    /**
     * 电动自行车充电功率异常检测平台
     *
     * @return
     */
    @PostMapping("queryTotal")
    public AjaxResult queryTotal() throws JsonProcessingException {
        // 查询累计已检测次数
        Long totalNumberDetectedTimes = sysOrderService.queryTotal();
        // 查询 result 和 markType 相等的次数
        Long equals = sysOrderService.resultEqualMarkType();

        // 计算综合准确率，避免整数除法误差
        double accuracy = (totalNumberDetectedTimes > 0) ? (double) equals / totalNumberDetectedTimes : 0.0;
        DecimalFormat df = new DecimalFormat("0.00");
        String intAccuracy = df.format(accuracy * 100);
        // 转换为 int
        int formattedAccuracy = (int) Double.parseDouble(intAccuracy);

        // 查询最新的订单号
        LambdaQueryWrapper<SysOrder> latestOrderWrapper = new LambdaQueryWrapper<>();
        latestOrderWrapper.select(SysOrder::getRecordNo)
                .orderByDesc(SysOrder::getCreateTime)
                .last("LIMIT 1");
        SysOrder latestOrder = sysOrderMapper.selectOne(latestOrderWrapper);
        String recordNo = (latestOrder != null) ? latestOrder.getRecordNo() : "N/A";

        // 查询不同 result 值的统计数量
        Integer result0 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getResult, 0));
        Integer result1 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getResult, 1));
        Integer result2 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getResult, 2));
        Integer result3 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getResult, 3));
        Integer result4 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getResult, 4));
        Integer result5 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getResult, 5));
        Integer resultNull = sysOrderMapper.selectCount(
                new LambdaQueryWrapper<SysOrder>()
                        .isNull(SysOrder::getResult) // 直接统计 NULL 值
                        .or(wrapper -> wrapper.notIn(SysOrder::getResult, 0, 1, 2, 3, 4, 5))
        );





        // 查询不同 markType 值的统计数量
        Integer markType0 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getMarkType, 0));
        Integer markType1 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getMarkType, 1));
        Integer markType2 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getMarkType, 2));


//        BigDecimal Mr0 = BigDecimal.valueOf(markType0)
//                .divide(BigDecimal.valueOf(totalNumberDetectedTimes), 2, RoundingMode.HALF_UP);
//        BigDecimal Mr1 = BigDecimal.valueOf(markType1)
//                .divide(BigDecimal.valueOf(totalNumberDetectedTimes), 2, RoundingMode.HALF_UP);
//        BigDecimal Mr2 = BigDecimal.valueOf(markType2)
//                .divide(BigDecimal.valueOf(totalNumberDetectedTimes), 2, RoundingMode.HALF_UP);


        BigDecimal Mr0 = BigDecimal.valueOf(markType0)
                .divide(BigDecimal.valueOf(totalNumberDetectedTimes), 2, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100)); // 乘以100
        Mr0 = Mr0.setScale(2, RoundingMode.HALF_UP); // 保留小数点后两位

        BigDecimal Mr1 = BigDecimal.valueOf(markType1)
                .divide(BigDecimal.valueOf(totalNumberDetectedTimes), 2, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100)); // 乘以100
        Mr1 = Mr1.setScale(2, RoundingMode.HALF_UP); // 保留小数点后两位

        BigDecimal Mr2 = BigDecimal.valueOf(markType2)
                .divide(BigDecimal.valueOf(totalNumberDetectedTimes), 2, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100)); // 乘以100
        Mr2 = Mr2.setScale(2, RoundingMode.HALF_UP); // 保留小数点后两位

        // 计算 markType 的占比（饼图数据）
/*
        double pipMarkType0 = (totalNumberDetectedTimes > 0) ? ((double) markType0 / totalNumberDetectedTimes * 100) : 0.0;
        double pipMarkType1 = (totalNumberDetectedTimes > 0) ? ((double) markType1 / totalNumberDetectedTimes * 100) : 0.0;
        double pipMarkType2 = (totalNumberDetectedTimes > 0) ? ((double) markType2 / totalNumberDetectedTimes * 100) : 0.0;
*/

// 计算 markType 的占比（饼图数据）
        double pipMarkType0 = (totalNumberDetectedTimes > 0) ? ((double) result0 / totalNumberDetectedTimes *100 ) : 0.0;
        double pipMarkType1 = (totalNumberDetectedTimes > 0) ? ((double) result1 / totalNumberDetectedTimes *100 ) : 0.0;
        double pipMarkType2 = (totalNumberDetectedTimes > 0) ? ((double) result2 / totalNumberDetectedTimes *100 ) : 0.0;

        double pipMarkType3 = (totalNumberDetectedTimes > 0) ? ((double) result3 / totalNumberDetectedTimes *100 ) : 0.0;
        double pipMarkType4 = (totalNumberDetectedTimes > 0) ? ((double) result4 / totalNumberDetectedTimes *100 ) : 0.0;
        double pipMarkType5 = (totalNumberDetectedTimes > 0) ? ((double) result5 / totalNumberDetectedTimes *100 ) : 0.0;

        double pipMarkTypeNull = (totalNumberDetectedTimes > 0) ? ((double) resultNull / totalNumberDetectedTimes * 100) : 0.0;



// 创建 DecimalFormat 对象，设置保留两位小数的格式
        DecimalFormat df0 = new DecimalFormat("0.00");

// 格式化并更新变量的值
        pipMarkType0 = Double.parseDouble(df0.format(pipMarkType0));
        pipMarkType1 = Double.parseDouble(df0.format(pipMarkType1));
        pipMarkType2 = Double.parseDouble(df0.format(pipMarkType2));

        // 查询 result 与 markType 相等的数量
        Integer markTypeEqualResult0 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getResult, 0).eq(SysOrder::getMarkType, 0));
        Integer markTypeEqualResult1 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getResult, 1).eq(SysOrder::getMarkType, 1));
        Integer markTypeEqualResult2 = sysOrderMapper.selectCount(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getResult, 2).eq(SysOrder::getMarkType, 2));

//        // 计算准确率，避免除以零异常
//        double accuracy0 = (markType0 > 0) ? ((double) markTypeEqualResult0 / markType0 *100) : 0.0;
//        double accuracy1 = (markType1 > 0) ? ((double) markTypeEqualResult1 / markType1 *100) : 0.0;
//        double accuracy2 = (markType2 > 0) ? ((double) markTypeEqualResult2 / markType2 *100) : 0.0;


        // 计算准确率，避免除以零异常
        DecimalFormat df3 = new DecimalFormat("#.00");
        double accuracy0 = (markType0 > 0) ? Double.parseDouble(df3.format((double) markTypeEqualResult0 / markType0 * 100)) : 0.0;
        double accuracy1 = (markType1 > 0) ? Double.parseDouble(df3.format((double) markTypeEqualResult1 / markType1 * 100)) : 0.0;
        double accuracy2 = (markType2 > 0) ? Double.parseDouble(df3.format((double) markTypeEqualResult2 / markType2 * 100)) : 0.0;


        // 根据订单号查询功率数据
        LambdaQueryWrapper<SysOrder> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(SysOrder::getRecordNo, recordNo)
                .orderByDesc(SysOrder::getCreateTime) // 按创建时间降序排序
                .last("LIMIT 1"); // 只取第一条记录

        SysOrder latestSysOrder = sysOrderMapper.selectOne(lambdaQueryWrapper);
        String powerList = latestSysOrder.getPowerList();

        Integer result = latestSysOrder.getResult();



        ObjectMapper objectMapper = new ObjectMapper();
        Integer[] powerArray = null;

        // 将字符串转换为整数数组
        try {
            powerArray = objectMapper.readValue(powerList, Integer[].class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("newRecordNo", recordNo); //正在检测订单号
        map1.put("totalNumberDetectedTimes", totalNumberDetectedTimes);//累计已检测次数
        map1.put("comprehensiveAccuracy", formattedAccuracy);//综合准确率

        map1.put("newRecordNoPowerList", powerArray);//综合准确率
        map1.put("result", result);//综合准确率

        HashMap<String, Object> map2 = new HashMap<>();

        // 结果数量
//        map2.put("actualNormality", result0);//正常         实际
//        map2.put("actualBatteryProblems", result1);//电瓶问题      实际
//        map2.put("actualChargeProblems", result2);//充电问题      实际

        map2.put("actualNormality",accuracy0);//正常         实际
        map2.put("actualBatteryProblems", accuracy1);//电瓶问题      实际
        map2.put("actualChargeProblems", accuracy2);//充电问题      实际


        HashMap<String, Object> map3 = new HashMap<>();
        // markType 统计
        map3.put("virtualNormality", markType0);  //正常 虚拟
        map3.put("virtualBatteryProblems", markType1); //电瓶问题 虚拟
        map3.put("virtualChargeProblems", markType2);//充电问题  虚拟

        HashMap<String, Object> map4 = new HashMap<>();
        // 饼图数据
        map4.put("pieNormality", pipMarkType0);//正常    饼图
        map4.put("pieBatteryProblems", pipMarkType1);//电瓶问题 饼图
        map4.put("pieChargeProblems", pipMarkType2);//充电问题 饼图

        map4.put("pipMarkType3",pipMarkType3);//
        map4.put("pipMarkType4",pipMarkType4);//
        map4.put("pipMarkType5",pipMarkType5);//
        map4.put("pipMarkTypeNull",pipMarkTypeNull);//

        //null 未检测成功



        HashMap<String, Object> map5 = new HashMap<>();
        //检测结果 0
        map5.put("testNormality", markType0); //电池正常数据
        map5.put("testNormalityRate", Mr0);// 电池正常 总检测次数占比
        map5.put("testNormalityAccuracyRate", accuracy0); //电池正常 准确率

        HashMap<String, Object> map6 = new HashMap<>();
        //检测结果 1
        map6.put("testBatteryProblems", markType1);//电瓶问题数据
        map6.put("testBatteryProblemsRate", Mr1);// 电瓶问题 总检测次数占比
        map6.put("testBatteryProblemsAccuracyRate", accuracy1);// 电瓶问题 电瓶问题准确率

        HashMap<String, Object> map7 = new HashMap<>();
        //检测结果 2
        map7.put("testPieChargeProblems", markType2); // 充电器问题问题数据
        map7.put("testPieChargeProblemsRate", Mr2);// 充电器问题 总检测次数占比
        map7.put("testPieChargeProblemsAccuracyRate", accuracy2);// 充电器问题 电瓶问题准确率




// 查询数据库中最新的创建时间
        LambdaQueryWrapper<SysOrder> latestDateWrapper = new LambdaQueryWrapper<>();
        latestDateWrapper.select(SysOrder::getCreateTime)
                .orderByDesc(SysOrder::getCreateTime)
                .last("LIMIT 1");
        SysOrder latestDateOrder = sysOrderMapper.selectOne(latestDateWrapper);

// 获取最新时间的日期部分，如果没有数据，则使用当前日期
        LocalDate today;
        if (latestDateOrder != null && latestDateOrder.getCreateTime() != null) {
            // 将 Date 类型的时间转换为 LocalDate
            Instant instant = latestDateOrder.getCreateTime().toInstant();
            today = instant.atZone(ZoneId.systemDefault()).toLocalDate(); // 获取日期部分
            System.out.println("我是最新的时间数据"+today);
        } else {
            today = LocalDate.now(); // 如果没有数据，则使用当前日期
        }

        // 获取今天的开始时间和结束时间
     //    LocalDate today = LocalDate.now();
       // LocalDate today = LocalDate.of(2025, 2, 10);
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);

        // 将 LocalDateTime 转换为 Date 类型，用于查询条件
        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

        // 构建查询条件
        LambdaQueryWrapper<SysOrder> wrapper = Wrappers.lambdaQuery();
        wrapper.between(SysOrder::getCreateTime, startDate, endDate)
        .last("LIMIT 10");  // 添加 LIMIT 20 来限制查询返回的记录数
        // 按照小时分组统计检测数量
        List<SysOrder> orders = sysOrderService.list(wrapper);

        Map<Integer, Integer> hourlyCounts = new HashMap<>();
        Map<Integer, Integer> hourlyEqualCounts = new HashMap<>();

        for (SysOrder order : orders) {
            Date createTimeDate = order.getCreateTime();
            if (createTimeDate != null) {
                // 将 Date 转换为 LocalDateTime
                LocalDateTime createTime = createTimeDate.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();
                int hour = createTime.getHour();

                // 统计每小时的订单数量
                hourlyCounts.put(hour, hourlyCounts.getOrDefault(hour, 0) + 1);

                // 统计每小时 mark_type 和 result 相等的订单数量
                if (order.getMarkType() != null && order.getResult() != null && order.getMarkType().equals(order.getResult())) {
                    hourlyEqualCounts.put(hour, hourlyEqualCounts.getOrDefault(hour, 0) + 1);
                }
            }
        }

        // 确保每个小时都有统计结果，没有检测的小时计为 0
        for (int i = 0; i < 24; i++) {
            hourlyCounts.putIfAbsent(i, 0);
            hourlyEqualCounts.putIfAbsent(i, 0);
        }

        // 整理结果
        List<Map<String, Object>> hourlyResultList = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            int totalCount = hourlyCounts.get(i);
            int equalCount = hourlyEqualCounts.get(i);
            double accuracys = totalCount > 0 ? (double) equalCount / totalCount : 0.0;

            Map<String, Object> hourlyResult = new HashMap<>();
            hourlyResult.put("hour",i);
            hourlyResult.put("totalCount", totalCount);
            hourlyResult.put("equalCount", equalCount);
            hourlyResult.put("accuracy", accuracys);
            hourlyResultList.add(hourlyResult);
        }


        HashMap<String, Object> totalMap = new HashMap<>();
        totalMap.put("map1", map1); //正在检测订单号 累计已检测次数  综合准确率
        totalMap.put("map2", map2); //实际   正常  电瓶问题  充电问题
        totalMap.put("map3", map3); //虚拟   正常  电瓶问题  充电问题
        totalMap.put("map4", map4); //饼图    正常  电瓶问题  充电问题
        totalMap.put("map5", map5);//电池正常数据   总检测次数占比       准确率
        totalMap.put("map6", map6);//电瓶问题数据   总检测次数占比       准确率
        totalMap.put("map7", map7);//充电器问题问题数据  总检测次数占比    准确率
        totalMap.put("map8", hourlyResultList);//

        return AjaxResult.success(totalMap);
    }


    /**
     * 今日实时检测情况
     * @return
     */
//    @PostMapping("/queryToday")
//    public AjaxResult queryToday(){
//
//        LambdaQueryWrapper<SysOrder> wrapper = new LambdaQueryWrapper<>();
//       //查询今天每个小时的检测数量
//
//
//
//
//
//        return null;
//    }

//    /**
//     * 今日实时检测情况
//     *
//     * @return
//     */
//    @PostMapping("/queryToday")
//    public AjaxResult queryToday() {
//        // 获取今天的开始时间和结束时间
//        // LocalDate today = LocalDate.now();
//        LocalDate today = LocalDate.of(2025, 2, 10);
//        LocalDateTime startOfDay = today.atStartOfDay();
//        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);
//
//        // 将 LocalDateTime 转换为 Date 类型，用于查询条件
//        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
//        Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
//
//        // 构建查询条件
//        LambdaQueryWrapper<SysOrder> wrapper = Wrappers.lambdaQuery();
//        wrapper.between(SysOrder::getCreateTime, startDate, endDate);
//
//        // 按照小时分组统计检测数量
//        List<SysOrder> orders = sysOrderService.list(wrapper);
//        Map<Integer, Integer> hourlyCounts = new HashMap<>();
//        for (SysOrder order : orders) {
//            Date createTimeDate = order.getCreateTime();
//            if (createTimeDate != null) {
//                // 将 Date 转换为 LocalDateTime
//                LocalDateTime createTime = createTimeDate.toInstant()
//                        .atZone(ZoneId.systemDefault())
//                        .toLocalDateTime();
//                int hour = createTime.getHour();
//                hourlyCounts.put(hour, hourlyCounts.getOrDefault(hour, 0) + 1);
//            }
//        }
//
//        // 确保每个小时都有统计结果，没有检测的小时计为 0
//        for (int i = 0; i < 24; i++) {
//            hourlyCounts.putIfAbsent(i, 0);
//        }
//
//        // 按小时排序
//        List<Map.Entry<Integer, Integer>> sortedEntries = new ArrayList<>(hourlyCounts.entrySet());
//        sortedEntries.sort(Map.Entry.comparingByKey());
//
//        // 组装结果
//        Map<String, Object> resultMap = new HashMap<>();
//        for (Map.Entry<Integer, Integer> entry : sortedEntries) {
//            resultMap.put(entry.getKey() + "hour", entry.getValue());
//        }
//
//        return AjaxResult.success(resultMap);
//    }


    /**
     * 今日  实时检测情况
     *
     * @return
     */
    @PostMapping("queryHourTotalRate")
    public AjaxResult queryHourTotalRate() {

        // 获取今天的开始时间和结束时间
        // LocalDate today = LocalDate.now();
        LocalDate today = LocalDate.of(2025, 2, 10);
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);

        // 将 LocalDateTime 转换为 Date 类型，用于查询条件
        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());

        // 构建查询条件
        LambdaQueryWrapper<SysOrder> wrapper = Wrappers.lambdaQuery();
        wrapper.between(SysOrder::getCreateTime, startDate, endDate);

        // 按照小时分组统计检测数量
        List<SysOrder> orders = sysOrderService.list(wrapper);
        Map<Integer, Integer> hourlyCounts = new HashMap<>();
        Map<Integer, Integer> hourlyEqualCounts = new HashMap<>();

        for (SysOrder order : orders) {
            Date createTimeDate = order.getCreateTime();
            if (createTimeDate != null) {
                // 将 Date 转换为 LocalDateTime
                LocalDateTime createTime = createTimeDate.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();
                int hour = createTime.getHour();

                // 统计每小时的订单数量
                hourlyCounts.put(hour, hourlyCounts.getOrDefault(hour, 0) + 1);

                // 统计每小时 mark_type 和 result 相等的订单数量
                if (order.getMarkType() != null && order.getResult() != null && order.getMarkType().equals(order.getResult())) {
                    hourlyEqualCounts.put(hour, hourlyEqualCounts.getOrDefault(hour, 0) + 1);
                }
            }
        }

        // 确保每个小时都有统计结果，没有检测的小时计为 0
        for (int i = 0; i < 24; i++) {
            hourlyCounts.putIfAbsent(i, 0);
            hourlyEqualCounts.putIfAbsent(i, 0);
        }

        // 整理结果
        List<Map<String, Object>> hourlyResultList = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            int totalCount = hourlyCounts.get(i);
            int equalCount = hourlyEqualCounts.get(i);
            double accuracy = totalCount > 0 ? (double) equalCount / totalCount : 0.0;

            Map<String, Object> hourlyResult = new HashMap<>();
            hourlyResult.put("hour", i + 1);
            hourlyResult.put("totalCount", totalCount);
            hourlyResult.put("equalCount", equalCount);
            hourlyResult.put("accuracy", accuracy);

            hourlyResultList.add(hourlyResult);
        }

        return AjaxResult.success(hourlyResultList);
    }


    /**
     * 查询每个小时的数据总检测次数
     * @return
     */
/*
    @PostMapping("/hour")
    public AjaxResult queryHour(@RequestBody HourDTO hourDTO) {

        Integer hour = hourDTO.getHour();

        // 构建查询条件，查询指定小时的所有订单
        LambdaQueryWrapper<SysOrder> wrapper = Wrappers.lambdaQuery();
        wrapper.select(SysOrder::getRecordNo) // 只选择订单号字段
                .ge(SysOrder::getCreateTime, getStartTimeOfHour(hour)) // 创建时间大于等于该小时的开始时间
                .lt(SysOrder::getCreateTime, getEndTimeOfHour(hour)); // 创建时间小于该小时的结束时间

        List<SysOrder> sysOrders = sysOrderMapper.selectList(wrapper);

        // 使用 ArrayList 的构造函数将 Stream 转换为 List
        List<String> recordNos = new ArrayList<>(Arrays.asList(sysOrders.stream()
                .map(SysOrder::getRecordNo)
                .toArray(String[]::new)));
        // 使用 Set 进行去重


        Set<String> recordNoSet = new HashSet<>(
                sysOrders.stream()
                .map(SysOrder::getRecordNo)
                .collect(Collectors.toList()));

//        int size = recordNoSet.size();
//        HashMap<Object, Object> map = new HashMap<>();
//        map.put("total",size);



        return AjaxResult.success(recordNoSet);
    }
*/
    /**
     * 查询每个小时的数据总检测次数
     * @return
     */


//    @PostMapping("/hour")
//    public AjaxResult queryHour(@RequestBody HourDTO hourDTO) {
//
//        Integer hour = hourDTO.getHour();
//
//        // 构建查询条件，查询指定小时的所有订单
//        LambdaQueryWrapper<SysOrder> wrapper = Wrappers.lambdaQuery();
//        wrapper.select(SysOrder::getRecordNo, SysOrder::getCreateTime) // 选择订单号和创建时间字段
//                .ge(SysOrder::getCreateTime, getStartTimeOfHour(hour)) // 创建时间大于等于该小时的开始时间
//                .lt(SysOrder::getCreateTime, getEndTimeOfHour(hour)); // 创建时间小于该小时的结束时间
//
//        List<SysOrder> sysOrders = sysOrderMapper.selectList(wrapper);
//        if (sysOrders == null) {
//            return AjaxResult.success(Collections.emptyList());
//        }
//
//        // 根据 recordNo 分组，取每组中 createTime 最大的记录
//        Map<String, SysOrder> distinctOrders = sysOrders.stream()
//                .filter(Objects::nonNull)
//                .filter(order -> order.getCreateTime() != null) // 过滤掉 createTime 为 null 的记录
//                .collect(Collectors.toMap(
//                        SysOrder::getRecordNo,
//                        order -> order,
//                        (existing, replacement) -> existing.getCreateTime().after(replacement.getCreateTime()) ? existing : replacement
//                ));
//
//        // 提取去重后的订单号
//        List<String> recordNos = distinctOrders.values().stream()
//                .map(SysOrder::getRecordNo)
//                .collect(Collectors.toList());
//
//
//
//
//
//        //获取这个小时中recordNos这些订单号 mark_type和result相等的数量
//        recordNos如果相等用最新的一条数据
//
//
//
//
//
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("total",recordNos.size());
//
//
//
//
//        return AjaxResult.success(recordNos);
//    }


    /**
     //     * 查询每个小时的数据总检测次数
     //     * @return
     //     */
//    @PostMapping("/hour")
//    public AjaxResult queryHour(@RequestBody HourDTO hourDTO) {
//
//        Integer hour = hourDTO.getHour();
//
//        // 构建查询条件，查询指定小时的所有订单
//        LambdaQueryWrapper<SysOrder> wrapper = Wrappers.lambdaQuery();
//        wrapper.select(SysOrder::getRecordNo, SysOrder::getCreateTime, SysOrder::getMarkType, SysOrder::getResult)
//                .ge(SysOrder::getCreateTime, getStartTimeOfHour(hour))
//                .lt(SysOrder::getCreateTime, getEndTimeOfHour(hour));
//
//        List<SysOrder> sysOrders = sysOrderMapper.selectList(wrapper);
//        if (sysOrders == null) {
//            return AjaxResult.success(Collections.emptyList());
//        }
//
//        // 根据 recordNo 分组，取每组中 createTime 最大的记录
//        Map<String, SysOrder> distinctOrders = sysOrders.stream()
//                .filter(Objects::nonNull)
//                .filter(order -> order.getCreateTime() != null)
//                .collect(Collectors.toMap(
//                        SysOrder::getRecordNo,
//                        order -> order,
//                        (existing, replacement) -> existing.getCreateTime().after(replacement.getCreateTime()) ? existing : replacement
//                ));
//
//        // 提取去重后的订单号
//        List<String> recordNos = distinctOrders.values().stream()
//                .map(SysOrder::getRecordNo)
//                .collect(Collectors.toList());
//
//        // 统计 mark_type 和 result 相等的数量
//        long equalCount = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getMarkType(), order.getResult()))
//                .count();
//
//
//
//        long result0 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getResult(), 0))
//                .count();
//
//        long result1 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getResult(), 1))
//                .count();
//
//        long result2 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getResult(), 2))
//                .count();
//
//
//
//
//        long markType0 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getMarkType(), 0))
//                .count();
//
//        long markType1 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getMarkType(), 1))
//                .count();
//        long markType2 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getMarkType(), 2))
//                .count();
//
//
//
//
//        // 将 recordNos.size() 转换为 BigDecimal 类型
//        BigDecimal recordNosSize = BigDecimal.valueOf(recordNos.size());
////        // 将 result0、result1、result2 转换为 BigDecimal 类型并进行除法运算
////        BigDecimal rate0 = BigDecimal.valueOf(result0).divide(recordNosSize, 2, BigDecimal.ROUND_HALF_UP);
////        BigDecimal rate1 = BigDecimal.valueOf(result1).divide(recordNosSize, 2, BigDecimal.ROUND_HALF_UP);
////        BigDecimal rate2 = BigDecimal.valueOf(result2).divide(recordNosSize, 2, BigDecimal.ROUND_HALF_UP);
//
//        // 将 result0、result1、result2 转换为 BigDecimal 类型并进行除法运算
//        // 计算比率并乘以 100，保留两位小数
//        BigDecimal rate0 = BigDecimal.valueOf(result0)
//                .divide(recordNosSize, 4, BigDecimal.ROUND_HALF_UP)
//                .multiply(BigDecimal.valueOf(100))
//                .setScale(2, BigDecimal.ROUND_HALF_UP);
//        BigDecimal rate1 = BigDecimal.valueOf(result1)
//                .divide(recordNosSize, 4, BigDecimal.ROUND_HALF_UP)
//                .multiply(BigDecimal.valueOf(100))
//                .setScale(2, BigDecimal.ROUND_HALF_UP);
//        BigDecimal rate2 = BigDecimal.valueOf(result2)
//                .divide(recordNosSize, 4, BigDecimal.ROUND_HALF_UP)
//                .multiply(BigDecimal.valueOf(100))
//                .setScale(2, BigDecimal.ROUND_HALF_UP);
//
//
//
//
//
//        // 新增：收集每个订单的详细信息
//        List<Map<String, Object>> orderDetails = new ArrayList<>();
//        distinctOrders.forEach((recordNo, order) -> {
//
//            Map<String, Object> detail = new HashMap<>();
//            detail.put("recordNo", order.getRecordNo());
//            detail.put("powerList", order.getPowerList());
//
//            // 如果需要其他字段（如 power_list），可以继续添加
//            orderDetails.add(detail);
//        });
//
//
//        HashMap<Object, Object> map1 = new HashMap<>();
//
//        map1.put("total", recordNos.size()); //检测次数
//        map1.put("equalCount", equalCount);
//        map1.put("rate", equalCount/recordNos.size()); //综合准确率
//        map1.put("recordNo", recordNos); //检测号码
//        map1.put("orderDetails", orderDetails);
//
//
//
//        HashMap<Object, Object> map2 = new HashMap<>();
//        map2.put("result0", result0); // 正常      真实
//        map2.put("result1", result1); //电瓶问题    真实
//        map2.put("result2", result2); //充电器问题   真实
//
//
//        HashMap<Object, Object> map3 = new HashMap<>();
//        map3.put("markType0", markType0);// 正常      虚拟
//        map3.put("markType1", markType1);//电瓶问题     虚拟
//        map3.put("markType2", markType2); //充电器问题   虚拟
//
//        HashMap<Object, Object> map4 = new HashMap<>();
//        map4.put("rate0", rate0); //正常        饼图比率
//        map4.put("rate1", rate1);//电瓶问题   饼图比率
//        map4.put("rate2", rate2);  //充电器问题   饼图比率
//
//
//        HashMap<Object, Object> totalHashMap = new HashMap<>();
//        totalHashMap.put("map1",map1);
//        totalHashMap.put("map2",map2);
//        totalHashMap.put("map3",map3);
//        totalHashMap.put("map4",map4);
//
//
//        return AjaxResult.success(totalHashMap);
//    }
//


    /**
     * 查询每个小时的详细数据
     *
     * @param hourDTO
     * @return
     */
//    @PostMapping("/hour")
//    public AjaxResult queryHour(@RequestBody HourDTO hourDTO) {
//
//        Integer hour = hourDTO.getHour();
//
//        // 构建查询条件，包含 power_list 字段
//        LambdaQueryWrapper<SysOrder> wrapper = Wrappers.lambdaQuery();
//        wrapper.select(
//                        SysOrder::getRecordNo,
//                        SysOrder::getCreateTime,
//                        SysOrder::getMarkType,
//                        SysOrder::getResult,
//                        SysOrder::getPowerList
//                )
//                .ge(SysOrder::getCreateTime, getStartTimeOfHour(hour))
//                .lt(SysOrder::getCreateTime, getEndTimeOfHour(hour));
//
//        List<SysOrder> sysOrders = sysOrderMapper.selectList(wrapper);
//        if (sysOrders == null) {
//            return AjaxResult.success(Collections.emptyList());
//        }
//
//        // 根据 recordNo 分组，取每组中 createTime 最大的记录
//        Map<String, SysOrder> distinctOrders = sysOrders.stream()
//                .filter(Objects::nonNull)
//                .filter(order -> order.getCreateTime() != null)
//                .collect(Collectors.toMap(
//                        SysOrder::getRecordNo,
//                        order -> order,
//                        (existing, replacement) -> existing.getCreateTime().after(replacement.getCreateTime()) ? existing : replacement
//                ));
//
//        // 提取去重后的订单号
//        List<String> recordNos = distinctOrders.values().stream()
//                .map(SysOrder::getRecordNo)
//                .collect(Collectors.toList());
//
//        // 统计 mark_type 和 result 相等的数量
//        long equalCount = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getMarkType(), order.getResult()))
//                .count();
//
//        // 统计 result 各值的数量
//        long result0 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getResult(), 0))
//                .count();
//        long result1 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getResult(), 1))
//                .count();
//        long result2 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getResult(), 2))
//                .count();
//
//        // 统计 mark_type 各值的数量
//        long markType0 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getMarkType(), 0))
//                .count();
//        long markType1 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getMarkType(), 1))
//                .count();
//        long markType2 = distinctOrders.values().stream()
//                .filter(order -> Objects.equals(order.getMarkType(), 2))
//                .count();
//
//        // 计算比率
//        BigDecimal recordNosSize = BigDecimal.valueOf(recordNos.size());
//        BigDecimal rate0 = calculateRate(result0, recordNosSize);
//        BigDecimal rate1 = calculateRate(result1, recordNosSize);
//        BigDecimal rate2 = calculateRate(result2, recordNosSize);
//
//        // 收集订单详情（包含 power_list）
//        List<Map<String, Object>> orderDetails = distinctOrders.values().stream()
//                .filter(order -> order.getPowerList() != null)
//                .map(order -> {
//                    Map<String, Object> detail = new HashMap<>();
//                    detail.put("recordNo", order.getRecordNo());
//                    detail.put("powerList", order.getPowerList());
//                    return detail;
//                })
//                .collect(Collectors.toList());
//
//        // 构建返回结果
//        Map<String, Object> map1 = new HashMap<>();
//        map1.put("total", recordNos.size());
//        map1.put("equalCount", equalCount);
//
//
//        double rate = (double) equalCount / (double) recordNos.size() * 100;
//        BigDecimal bd = new BigDecimal(rate);
//        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
//        double finalRate = bd.doubleValue();
//
//        map1.put("rate", finalRate);
//
//        map1.put("recordNo", recordNos);
//        map1.put("orderDetails", orderDetails);
//
//        Map<String, Object> map2 = new HashMap<>();
//        map2.put("result0", result0);
//        map2.put("result1", result1);
//        map2.put("result2", result2);
//
//        Map<String, Object> map3 = new HashMap<>();
//        map3.put("markType0", markType0);
//        map3.put("markType1", markType1);
//        map3.put("markType2", markType2);
//
//        Map<String, Object> map4 = new HashMap<>();
//        map4.put("rate0", rate0);
//        map4.put("rate1", rate1);
//        map4.put("rate2", rate2);
//
//        Map<String, Object> totalHashMap = new HashMap<>();
//        totalHashMap.put("map1", map1);
//        totalHashMap.put("map2", map2);
//        totalHashMap.put("map3", map3);
//        totalHashMap.put("map4", map4);
//
//        return AjaxResult.success(totalHashMap);
//    }

    @PostMapping("/hour")
    public AjaxResult queryHour(@RequestBody HourDTO hourDTO) {
        Integer hour = hourDTO.getHour();
        // 构建查询条件，包含 power_list 字段
        LambdaQueryWrapper<SysOrder> wrapper = Wrappers.lambdaQuery();
        wrapper.select(
                        SysOrder::getRecordNo,
                        SysOrder::getCreateTime,
                        SysOrder::getMarkType,
                        SysOrder::getResult,
                        SysOrder::getPowerList
                )
                .ge(SysOrder::getCreateTime, getStartTimeOfHour(hour))
                .lt(SysOrder::getCreateTime, getEndTimeOfHour(hour))
                .last("LIMIT 10");  // 添加 LIMIT 20 来限制查询返回的记录数

        List<SysOrder> sysOrders = sysOrderMapper.selectList(wrapper);
        if (sysOrders == null || sysOrders.isEmpty()) {
            return AjaxResult.success(Collections.emptyMap()); // 避免后续计算异常
        }

        // 根据 recordNo 分组，取每组中 createTime 最大的记录
        Map<String, SysOrder> distinctOrders = new HashMap<>();
        for (SysOrder order : sysOrders) {
            if (order == null || order.getCreateTime() == null) {
                continue;
            }
            distinctOrders.merge(order.getRecordNo(), order,
                    (existing, replacement) -> existing.getCreateTime().after(replacement.getCreateTime()) ? existing : replacement);
        }

        List<String> recordNos = new ArrayList<>(distinctOrders.keySet());

        // 避免 0 除法错误
        int totalRecords = recordNos.size();
        if (totalRecords == 0) {
            return AjaxResult.success(Collections.emptyMap());
        }

        // 统计 mark_type 和 result 相等的数量
        long equalCount = 0;
        Map<Integer, Long> resultCount = new HashMap<>();
        Map<Integer, Long> markTypeCount = new HashMap<>();

        for (SysOrder order : distinctOrders.values()) {
            if (Objects.equals(order.getMarkType(), order.getResult())) {
                equalCount++;
            }

            resultCount.put(order.getResult(), resultCount.getOrDefault(order.getResult(), 0L) + 1);
            markTypeCount.put(order.getMarkType(), markTypeCount.getOrDefault(order.getMarkType(), 0L) + 1);
        }

        // 计算比率
        BigDecimal totalBigDecimal = BigDecimal.valueOf(totalRecords);
        BigDecimal rate0 = calculateRate(resultCount.getOrDefault(0, 0L), totalBigDecimal);
        BigDecimal rate1 = calculateRate(resultCount.getOrDefault(1, 0L), totalBigDecimal);
        BigDecimal rate2 = calculateRate(resultCount.getOrDefault(2, 0L), totalBigDecimal);

        // 收集订单详情（包含 power_list）
        List<Map<String, Object>> orderDetails = new ArrayList<>();
        for (SysOrder order : distinctOrders.values()) {
            if (order.getPowerList() != null) {
                Map<String, Object> detail = new HashMap<>();
                detail.put("recordNo", order.getRecordNo());
                detail.put("powerList", order.getPowerList());
                orderDetails.add(detail);
            }
        }



        // 构建返回结果
        Map<String, Object> totalHashMap = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("total", totalRecords);
        map1.put("equalCount", equalCount);


        double rate = (double) equalCount / totalRecords * 100;
        DecimalFormat df = new DecimalFormat("#.00");
        String formattedRate = df.format(rate);
        double finalRate = Double.parseDouble(formattedRate);

        System.out.println("equalCount"+equalCount);
        System.out.println("totalRecords"+totalRecords);

        map1.put("rate",finalRate);
        map1.put("recordNo", recordNos);
        map1.put("orderDetails", orderDetails);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("result0", resultCount.getOrDefault(0, 0L));
        map2.put("result1", resultCount.getOrDefault(1, 0L));
        map2.put("result2", resultCount.getOrDefault(2, 0L));

        Map<String, Object> map3 = new HashMap<>();
        map3.put("markType0", markTypeCount.getOrDefault(0, 0L));
        map3.put("markType1", markTypeCount.getOrDefault(1, 0L));
        map3.put("markType2", markTypeCount.getOrDefault(2, 0L));

        Map<String, Object> map4 = new HashMap<>();
        map4.put("rate0", rate0);
        map4.put("rate1", rate1);
        map4.put("rate2", rate2);

        totalHashMap.put("map1", map1);
        totalHashMap.put("map2", map2);
        totalHashMap.put("map3", map3);
        totalHashMap.put("map4", map4);

        return AjaxResult.success(totalHashMap);
    }


    private BigDecimal calculateRate(long count, BigDecimal total) {
        return BigDecimal.valueOf(count)
                .divide(total, 4, BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(100))
                .setScale(2, BigDecimal.ROUND_HALF_UP);
    }




    // 辅助方法：获取指定小时的开始时间（基于最新记录的当天）
    private java.sql.Timestamp getStartTimeOfHour(int hour) {
        // 获取最新记录的日期
        LocalDate latestDate = getLatestDateFromDatabase();
        // 根据该日期和指定的小时计算当天的开始时间
        java.time.LocalDateTime startTime = latestDate.atTime(hour, 0, 0, 0);
        return java.sql.Timestamp.valueOf(startTime);
    }

    // 辅助方法：获取指定小时的结束时间（基于最新记录的当天）
    private java.sql.Timestamp getEndTimeOfHour(int hour) {
        // 获取最新记录的日期
        LocalDate latestDate = getLatestDateFromDatabase();
        // 根据该日期和指定的小时计算当天的结束时间
        java.time.LocalDateTime endTime = latestDate.atTime(hour, 59, 59, 999999999);
        return java.sql.Timestamp.valueOf(endTime);
    }

    // 获取最新记录的日期部分
    private LocalDate getLatestDateFromDatabase() {
        // 查询数据库中最新的创建时间
// 查询数据库中最新的创建时间
        LambdaQueryWrapper<SysOrder> latestDateWrapper = new LambdaQueryWrapper<>();
        latestDateWrapper.select(SysOrder::getCreateTime)
                .orderByDesc(SysOrder::getCreateTime)
                .last("LIMIT 1");
        SysOrder latestOrder = sysOrderMapper.selectOne(latestDateWrapper);

        // 如果数据库没有记录，返回当前日期
        if (latestOrder != null && latestOrder.getCreateTime() != null) {
            // 将 Date 转换为 LocalDate
            java.util.Date createTime = latestOrder.getCreateTime();
            Instant instant = createTime.toInstant();
            System.out.println("我是hour的时间"+instant);
            return instant.atZone(ZoneId.systemDefault()).toLocalDate();
        } else {
            return LocalDate.now(); // 如果没有数据，返回当前日期
        }
    }















    // 辅助方法：获取指定日期的开始时间（00:00:00）
    private java.sql.Timestamp getStartTimeOfDay(LocalDate date) {
        java.time.LocalDateTime startOfDay = date.atStartOfDay();
        return java.sql.Timestamp.valueOf(startOfDay);
    }

    // 辅助方法：获取指定日期的结束时间（23:59:59）
    private java.sql.Timestamp getEndTimeOfDay(LocalDate date) {
        java.time.LocalDateTime endOfDay = date.atTime(23, 59, 59, 999999999);
        return java.sql.Timestamp.valueOf(endOfDay);
    }




    //    // 辅助方法：获取指定小时的开始时间
//    private java.sql.Timestamp getStartTimeOfHour(int hour) {
//        java.time.LocalDateTime now = java.time.LocalDateTime.now();
//        java.time.LocalDateTime startTime = now.withHour(hour).withMinute(0).withSecond(0).withNano(0);
//        return java.sql.Timestamp.valueOf(startTime);
//    }
//
//    // 辅助方法：获取指定小时的结束时间
//    private java.sql.Timestamp getEndTimeOfHour(int hour) {
//        java.time.LocalDateTime now = java.time.LocalDateTime.now();
//        java.time.LocalDateTime endTime = now.withHour(hour).withMinute(59).withSecond(59).withNano(999999999);
//        return java.sql.Timestamp.valueOf(endTime);
//    }
    // 辅助方法：获取指定日期和小时的开始时间
/*    private java.sql.Timestamp getStartTimeOfHour(int hour) {
        // 指定日期为 2025 年 10 月 2 日
        java.time.LocalDateTime specifiedDate = LocalDateTime.of(2025, 2, 10, hour, 0, 0, 0);
        return java.sql.Timestamp.valueOf(specifiedDate);
    }

    // 辅助方法：获取指定日期和小时的结束时间
    private java.sql.Timestamp getEndTimeOfHour(int hour) {
        // 指定日期为 2025 年 10 月 2 日
        java.time.LocalDateTime specifiedDate = LocalDateTime.of(2025, 2, 10, hour, 59, 59, 999999999);
        return java.sql.Timestamp.valueOf(specifiedDate);
    }*/


    /**
     * 根据订单号查询
     */
        @PostMapping("queryOrderByrecordNos")
        public AjaxResult queryOrderByrecordNos(@RequestBody HourDTO hourDTO) {
            List<String> recordNos = hourDTO.getRecordNos();
            LambdaQueryWrapper<SysOrder> wrapper = new LambdaQueryWrapper<>();

                wrapper.in(SysOrder::getRecordNo, recordNos);

            // 按照创建时间降序排列
            wrapper.orderByDesc(SysOrder::getCreateTime);
            // 分组查询每个订单号对应的最新记录
            wrapper.groupBy(SysOrder::getRecordNo);

            List<SysOrder> sysOrders = sysOrderMapper.selectList(wrapper);

            // 查询result和mark_type相等的数量
            int equalCount = 0;
            for (SysOrder order : sysOrders) {
                if (order.getResult() != null && order.getMarkType() != null && order.getResult().equals(order.getMarkType())) {
                    equalCount++;
                }
                System.out.println("HJHH"+order.getRecordNo()+"---------"+order.getCreateTime());
            }


            List<SysOrder> resultZeroOrders0 = new ArrayList<>();
            for (SysOrder order : sysOrders) {
                if (order.getResult() != null && order.getResult() == 0) {
                    resultZeroOrders0.add(order);
                }
            }
            int result0 = resultZeroOrders0.size();


            List<SysOrder> resultZeroOrders1 = new ArrayList<>();
            for (SysOrder order : sysOrders) {
                if (order.getResult() != null && order.getResult() == 1) {
                    resultZeroOrders1.add(order);
                }
            }
            int result1 = resultZeroOrders1.size();


            List<SysOrder> resultZeroOrders2 = new ArrayList<>();
            for (SysOrder order : sysOrders) {
                if (order.getResult() != null && order.getResult() == 2) {
                    resultZeroOrders2.add(order);
                }
            }
            int result2 = resultZeroOrders2.size();



            List<SysOrder> mark0= new ArrayList<>();
            for (SysOrder order : sysOrders) {
                if (order.getMarkType() != null && order.getMarkType()== 0) {
                    mark0.add(order);
                }
            }
            int markType0 = mark0.size();


            List<SysOrder> mark1= new ArrayList<>();
            for (SysOrder order : sysOrders) {
                if (order.getMarkType() != null && order.getMarkType()== 1) {
                    mark1.add(order);
                }
            }
            int markType1 = mark1.size();


            List<SysOrder> mark2= new ArrayList<>();
            for (SysOrder order : sysOrders) {
                if (order.getMarkType() != null && order.getMarkType()== 2) {
                    mark2.add(order);
                }
            }
            int markType2 = mark2.size();

            // 构建每个 recordNo 对应的 power_list 数据
//            Map<String, List<String>> recordNoPowerListMap = new HashMap<>();
//            for (SysOrder order : sysOrders) {
//                String recordNo = order.getRecordNo();
//                String powerList = order.getPowerList();
//                //recordNoPowerListMap.computeIfAbsent(recordNo, k -> new ArrayList<>()).add(powerList);
//
//                List<String> powerListList = recordNoPowerListMap.get(recordNo);
//                if (powerListList == null) {
//                    powerListList = new ArrayList<>();
//                    recordNoPowerListMap.put(recordNo, powerListList);
//                }
//                powerListList.add(powerList);
//            }
            // 构建 orderDetails 数组
            List<Map<String, Object>> orderDetails = new ArrayList<>();
            for (SysOrder order : sysOrders) {
                Map<String, Object> detail = new HashMap<>();
                detail.put("recordNo", order.getRecordNo());
                detail.put("powerList", order.getPowerList());
                orderDetails.add(detail);
            }
//            Map<Object, Object> map01 = new HashMap<>();
//            map01.put("recordNo", recordNos);
//            map01.put("powerList", recordNoPowerListMap);;

            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("total", recordNos.size());

            double rate = (double) equalCount / recordNos.size() * 100;
            DecimalFormat df = new DecimalFormat("#.00");
            String formattedRate = df.format(rate);
            double finalRate = Double.parseDouble(formattedRate);

            map1.put("rate",finalRate);

            System.out.println("equalCount"+equalCount);
            System.out.println("totalRecords"+recordNos.size());

            //map1.put("rate",equalCount/recordNos.size()*100);
            map1.put("recordNo",recordNos);
            map1.put("equalCount",equalCount);
            map1.put("orderDetails", orderDetails); // 直接使用数组


            HashMap<Object, Object> map = new HashMap<>();

            map.put("recordNos", recordNos);

            HashMap<String, Object> map2 = new HashMap<>();

            map2.put("result0", result0);
            map2.put("result1", result1);
            map2.put("result2", result2);

            HashMap<String, Object> map3 = new HashMap<>();
            map3.put("markType0", markType0);
            map3.put("markType1", markType1);
            map3.put("markType2", markType2);


            HashMap<String, Object> map4 = new HashMap<>();


            double rate0 = (double) result0/recordNos.size() * 100;
//            BigDecimal bd0 = new BigDecimal(rate0);
//            bd0 = bd0.setScale(2, BigDecimal.ROUND_HALF_UP);
//            double finalRate0 = bd0.doubleValue();
//
//            double rate1 = result1/recordNos.size() * 100;
//            BigDecimal bd1 = new BigDecimal(rate1);
//            bd1 = bd1.setScale(2, BigDecimal.ROUND_HALF_UP);
//            double finalRate1 = bd1.doubleValue();
//
//
//            double rate2 = result2/recordNos.size() * 100;
//            BigDecimal bd2 = new BigDecimal(rate2);
//            bd2 = bd2.setScale(2, BigDecimal.ROUND_HALF_UP);
//            double finalRate2 = bd2.doubleValue();

            double rate00 = ((double) result0 / recordNos.size()) * 100;
            BigDecimal bd0 = BigDecimal.valueOf(rate00).setScale(2, RoundingMode.HALF_UP);
            double finalRate0 = bd0.doubleValue();

            double rate1 = ((double) result1 / recordNos.size()) * 100; // 关键：强制转换 result1 为 double
            BigDecimal bd1 = BigDecimal.valueOf(rate1).setScale(2, RoundingMode.HALF_UP);
            double finalRate1 = bd1.doubleValue();

            double rate2 = ((double) result2 / recordNos.size()) * 100;
            BigDecimal bd2 = BigDecimal.valueOf(rate2).setScale(2, RoundingMode.HALF_UP);
            double finalRate2 = bd2.doubleValue();
            
            map4.put("rate0", finalRate0);
            map4.put("rate1", finalRate1);
            map4.put("rate2", finalRate2);



//            map4.put("rate0", result0/recordNos.size());
//            map4.put("rate1", result1/recordNos.size());
//            map4.put("rate2", result2/recordNos.size());

            HashMap<String, Object> resutMap = new HashMap<>();
            resutMap.put("map1",map1);
            resutMap.put("map2",map2);
            resutMap.put("map3",map3);
            resutMap.put("map4",map4);

            return AjaxResult.success(resutMap);
        }






    @PostMapping("queryAllRecordNos")
    public AjaxResult queryAllRecordNos(@RequestBody RecordNoDTO recordNoDTO) {

        Integer hour = recordNoDTO.getHour();
        String recordNo = recordNoDTO.getRecordNo();
        LambdaQueryWrapper<SysOrder> wrapper = new LambdaQueryWrapper<>();

        // 确保 recordNo 既不为 null 也不为空
        if (recordNo != null ||recordNo !="") {
            wrapper.like(SysOrder::getRecordNo, recordNo);
        }

        // 根据 createTime 降序排序，获取最近的记录
        wrapper.orderByDesc(SysOrder::getCreateTime);

        if (hour != null) {
            wrapper.ge(SysOrder::getCreateTime, getStartTimeOfHour(hour)).lt(SysOrder::getCreateTime, getEndTimeOfHour(hour));
        }

        if(recordNoDTO.getCount()!=null){
            // 查询符合条件的前10条记录
            wrapper.last("LIMIT "+recordNoDTO.getCount());
        }


        // 查询符合条件的 SysOrder 记录
        List<SysOrder> sysOrders = sysOrderMapper.selectList(wrapper);

        // 将查询结果转为 RecordNoVO 列表
        ArrayList<RecordNoVO> recordNoVOS = new ArrayList<>();
        for (SysOrder sysOrder : sysOrders) {
            RecordNoVO recordNoVO = new RecordNoVO();
            recordNoVO.setRecordNos(sysOrder.getRecordNo());
            recordNoVOS.add(recordNoVO);
        }

        // 返回查询结果
        return AjaxResult.success(recordNoVOS);
    }












}



